"""
数据验证工具
"""
import re
from datetime import datetime, date


def is_valid_email(email):
    """验证邮箱格式"""
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email) is not None


def is_valid_phone(phone):
    """验证手机号格式"""
    pattern = r'^1[3-9]\d{9}$'
    return re.match(pattern, phone) is not None


def is_valid_date(date_str, date_format='%Y-%m-%d'):
    """验证日期格式"""
    try:
        datetime.strptime(date_str, date_format)
        return True
    except (ValueError, TypeError):
        return False


def is_valid_id_card(id_card):
    """验证身份证号格式"""
    # 简单的18位身份证验证
    pattern = r'^[1-9]\d{5}(19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$'
    return re.match(pattern, id_card) is not None


def validate_date_range(start_date, end_date):
    """验证日期范围是否合理"""
    if not start_date or not end_date:
        return False, "开始日期和结束日期不能为空"
    
    if isinstance(start_date, str):
        try:
            start_date = datetime.strptime(start_date, '%Y-%m-%d').date()
        except ValueError:
            return False, "开始日期格式不正确"
    
    if isinstance(end_date, str):
        try:
            end_date = datetime.strptime(end_date, '%Y-%m-%d').date()
        except ValueError:
            return False, "结束日期格式不正确"
    
    if start_date > end_date:
        return False, "开始日期不能晚于结束日期"
    
    return True, "日期范围有效"


def validate_positive_number(value, field_name="数值"):
    """验证正数"""
    try:
        num = float(value)
        if num <= 0:
            return False, f"{field_name}必须为正数"
        return True, f"{field_name}有效"
    except (ValueError, TypeError):
        return False, f"{field_name}必须为数字"


def validate_percentage(value):
    """验证百分比（0-100）"""
    try:
        num = float(value)
        if not 0 <= num <= 100:
            return False, "百分比必须在0-100之间"
        return True, "百分比有效"
    except (ValueError, TypeError):
        return False, "百分比必须为数字"


def validate_required_fields(data, required_fields):
    """验证必填字段"""
    missing_fields = []
    for field in required_fields:
        if field not in data or not data[field]:
            missing_fields.append(field)
    
    if missing_fields:
        return False, f"缺少必填字段: {', '.join(missing_fields)}"
    
    return True, "所有必填字段已填写"